<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Util\UploadFile;

/**
 * 单位信息管理
 * Class QuitController
 * @package Admin\Controller
 */
class QuitController extends AdminController {

    /**
     * 系统管理 -> 政务公开 -> 政务分类管理 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出单位信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("quit")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->display();
    }

    /**
     * 单位信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $quit = M("quit")->where(array("id"=>$dataId))->find();
        $this->assign("quit", $quit);

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);
        $this->assign("opinion", $this->fn_GetOpinionList());

        if($quit['state']=='待房产局审核'){
            //读取用户已交押金数，及押金编号
            $this->assign("yajin", $this->fn_GetYajinByContactNo($quit['contact_no']));
        }

        //渲染加入黑名单对话框
        $this->Render_BlacklistDialog($quit);
        $this->display();
    }

    public function fn_GetYajinByContactNo($cno){
        return M("contact c")->field("p.amount, p.name")
            ->join(C("DB_PREFIX")."payments p on c.no = p.contact_no", "LEFT")
            ->where(array("c.no"=>$cno, "p.type"=>'收', "p.ptype"=>array("like", "%押金")))->find();
    }

    public function ajax_wuye(){

        $qid = I("post.id");
        if(!$qid){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            //读取退出申请数据
            $quit = M("quit")->where(array("id"=>$qid))->find();
            if(!$quit){
                $this->error("系统错误，数据不存在");
            }

            //修改申请状态为待房产局审核
            $data = array(
                "state" => "待房产局审核",
                "opinion" => I("post.spyj"),
                "wy_user" => session("username"),
                "wy_date" => I("post.sprq"),
            );
            $res = M("quit")->where(array("id"=>$qid))->save($data);
            if(!$res){
                $this->error("系统异常，审批无法提交");
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");
        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function ajax_fcj(){

        $qid = I("post.id");
        if(!$qid){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            //读取退出申请数据
            $quit = M("quit")->where(array("id"=>$qid))->find();
            if(!$quit){
                $this->error("系统错误，数据不存在");
            }

            //修改申请状态为待已退出
            $data = array(
                "state" => "已退出",
                "opinion2" => I("post.spyj"),
                "wy_user2" => session("username"),
                "wy_date2" => I("post.sprq2"),
                "utime" => time()
            );
            $res = M("quit")->where(array("id"=>$qid))->save($data);
            if(!$res){
                $this->error("系统异常，审批无法提交");
            }

            //设置申请状态为：退出
            $res = $this->fn_MarkApplyRefused($quit['yw_no']);
            if(!$res){
                $this->error("系统异常，申请状态更新失败");
            }

            //增加申请的退出审批记录，标识保障退出
            $res = $this->fn_AddShenpiLog($quit['yw_no'], I("post.spyj"));
            if(!$res){
                $this->error("系统异常，添加审批记录失败");
            }

            //押金缴纳记录判断
            $pay = $this->fn_GetYajinByContactNo($quit['contact_no']);
            if($pay){
				//增加一条支付记录（付），备注为退还押金
				$res = $this->fn_RefundRentalYj($quit, $pay);
				if(!$res){
					$this->error("系统异常，创建押金退还记录失败");
				}
                //$this->error("系统异常，押金缴纳没有找到");
            }

            //设置房源为空置状态
            $res = $this->fn_MarkHouseEmpty($quit['house_no']);
            if(!$res){
                $this->error("系统异常，更新房源状态失败");
            }

            //增加房源租赁记录
            $res = $this->fn_AddHouseRentalLog($quit, $data);
            if(!$res){
                $this->error("系统异常，增加房源租赁记录失败");
            }

            //将该申请人列入黑名单2年
            $res = $this->fn_addBlacklist($quit, 2);
            if(!$res){
                $this->error("系统异常，将申请人信息列入黑名单失败");
            }

            //将该申请人的配偶列入黑名单2年
            $peiou = $this->fn_GetPeiOuInfo($quit['yw_no']);
            if($peiou){
                $res = $this->fn_addBlacklist($peiou, 2);
                if(!$res){
                    $this->error("系统异常，将申请人配偶信息列入黑名单失败");
                }
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");
        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function ajax_updateDate(){

        $qid = I("post.id");
        if(!$qid){
            $this->error("缺少必要参数");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            //读取退出申请数据
            $quit = M("quit")->where(array("id"=>$qid))->find();
            if(!$quit){
                $this->error("系统错误，数据不存在");
            }

            $res = M("quit")->where(array("id"=>$qid))->save(array(
                "ctime" => I("post.ctime"),
                "wy_date" => I("post.wy_date"),
                "wy_date2" => I("post.wy_date2"),
            ));
            if(!$res){
                $this->error("系统错误，日期修改失败");
            }

            if($quit['state']=='已退出' && I("post.wy_date2")){
                $res = M("house_log")->where(array("yw_no"=>$quit['yw_no']))
                    ->save(array("date2" => I("post.wy_date2")));
                /*if(!$res){
                    $this->error(M("house_log")->getLastSql());
                    $this->error("系统错误，日期同步失败");
                }*/
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");
        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    protected function fn_AddHouseRentalLog($quit, $data){
        $contact = M("contact")->where()->find();
        if($contact){
            $rental = array(
                "remarks"=> $quit['reason'],
                "cuser"=> self::$u["username"],
                "date1"=> $contact['ksrq'],
                "date2"=> $data['wy_date2'],
                "ctime"=> date("Y/m/d"),
                "house_no"=> $quit["house_no"],
                "bzdx"=> $quit['name'],
                "idno"=> $quit['idno'],
            );
            return M("house_log")->add($rental);
        }
        $this->error("租赁合同没有找到，请联系管理员");
    }

    private function fn_GeneratePaymentsNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("payments_no")->add($data);
        return "P".$no;
    }

    public function fn_addBlacklist($info, $year){
        $zxtime = time() + 365*24*3600*intval($year);
        $data = array(
            "name" => $info["name"],
            "idno" => $info["idno"],
            "phone" => $info["phone"],
            "reason" => "退出保障",
            "zxtime" => $zxtime,
            "zxyear" => $year,
            "cuser" => session("username"),
            "ctime" => date("Y/m/d"),
        );
        return M("blacklist")->add($data);
    }

    public function fn_GetPeiOuInfo($no){
        $prefix = substr($no, 0, 1);
        if($prefix=="L"){
            $where = array("lzf_no"=>$no, "relation"=>"配偶");
            return M("lzf_family")->field("name,idno,gender,phone")->where($where)->find();
        }else if($prefix=="G"){
            $where = array("gzf_no"=>$no, "relation"=>"配偶");
            return M("gzf_family")->field("name,idno,gender,phone")->where($where)->find();
        }else if($prefix=="Z" || $prefix=="S"){
            return array();
        }else{
            $this->error("无效的申请编号");
        }
    }

    /**
     * 设置房源状态为：租赁中
     * @param $houseId 房源ID
     * @param $no 申请编号
     * @param $contactId 合同ID
     * @param $rq 分配日期
     */
    protected function fn_MarkHouseEmpty($house_no){
        $data = array(
            "rzdate"=> null, "state" => "闲置中",
            "zhname" => null, "zhidno" => null,
            "zhname2" => null, "zhidno2" => null,
            "jtnum" => null,  "dbnum" => null,
            "dibaohm" => null,  "phone" => null,
            "yw_no"=> null, "contact_no"=> null, "utime"=> time(),
        );
        return M("house")->where(array("name"=>$house_no))->save($data);
    }

    protected function fn_RefundRentalYj($quit, $pay){
        $payment = array(
            "name" => $this->fn_GeneratePaymentsNo(),
            "contact_no" => $quit['contact_no'],
            "amount" => $pay['amount'],
            "type" => "付", //收，付
            "house_no" => $pay['house_no'],
            "house_addr" => $pay['house_addr'],
            "payer" => $quit['name'],
            "payer_idno" => $quit['idno'],
            "pdate" => date("Y/m/d"),
            "remarks" => "退还押金",
            "cuser" => session("username"),
            "ctime" => time()
        );
        $prefix = substr($quit['yw_no'], 0, 1);
        if($prefix=="L"){
            $payment['ptype'] = "廉租房押金";
            return M("payments")->add($payment);
        }else if($prefix=="G"){
            $payment['ptype'] = "公租房押金";
            return M("payments")->add($payment);
        }else if($prefix=="S"){
            $payment['ptype'] = "商业用房押金";
            return M("payments")->add($payment);
        }else if($prefix=="Z"){
            $payment['ptype'] = "直管公房押金";
            return M("payments")->add($payment);
        }else{
            $this->error("无效的申请编号");
        }
    }

    protected function fn_AddShenpiLog($no, $opinion, $state='同意'){
        $log = array(
            "spr" => self::$u["username"],
            "spdw" => self::$u["company_name"],
            "sphj" => "保障退出",
            "spyj" => $opinion,
            "spzt" => $state,
            "sptime" => time(),
        );
        $prefix = substr($no, 0, 1);
        if($prefix=="L"){
            $log['lzf_no'] = $no;
            return M("lzf_log")->add($log);
        }else if($prefix=="G"){
            $log['gzf_no'] = $no;
            return M("gzf_log")->add($log);
        }else if($prefix=="Z" || $prefix=="S"){
            return true;
        }else{
            $this->error("无效的申请编号");
        }
    }

    protected function fn_MarkApplyRefused($no){
        $prefix = substr($no, 0, 1);
        if($prefix=="L"){
            $data = array("state"=>"refuse", "utime"=>time());
            return M("lzf")->where(array("no"=>$no))->save($data);
        }else if($prefix=="G"){
            $data = array("state"=>"refuse", "utime"=>time());
            return M("gzf")->where(array("no"=>$no))->save($data);
        }else if($prefix=="Z" || $prefix=="S"){
            $data = array("state"=>"已退出", "utime"=>time());
            return M("menmian")->where(array("no"=>$no))->save($data);
        }else{
            $this->error("无效的申请编号");
        }
    }

    protected function fn_GetOpinionList(){
        return M("opinion")->where()->order("seq asc")->select();
    }

    /**
     * 单位信息维护 -> 新增
     */
    public function add(){
        if(IS_POST){    //添加公司信息
            $data = array(
                "name" => I("post.name"),
                "idno" => I("post.idno"),
                "phone" => I("post.phone"),
                "house_addr" => I("post.house_addr"),
                "house_no" => I("post.house_no"),
                "contact_no" => I("post.contact_no"),
                "yw_no" => I("post.yw_no"),
                "reason" => I("post.reason"),
                "remarks" => I("post.remarks"),
                "state" => "待物业审核",
                "ctime" => date("Y/m/d"),
                "cuser" => session("username"),
            );
            $dataId = M("quit")->add($data);
            if($dataId){
                header("Location:/admin/quit/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建保障退出申请失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $quit = M("quit")->where(array("id"=>I("get.id")))->find();
            $this->assign("quit", $quit);
        }

        $this->display();
    }

    /**
     * 房屋自动补全搜索算法
     */
    public function ajax_SearchHouseByName(){
        $h = array();
        $where = array("state"=>"租赁中", "name"=>array("like", "%".I("get.house")."%"));
        $house = M("house")->where($where)->select();
        foreach ($house as $v){
            array_push($h, array("value"=>$v["name"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.house"),'suggestions' => $h));
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("quit")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("quit")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("quit")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array();
        if(I("request.value")){
            if(I("request.field")=="batch_id"){ //多表查询处理
                $dataIds = $this->fn_SelectBatchByName(I("request.value"));
                $where[I("request.field")] = array("in", $dataIds);
            }else{
                $where[I("request.field")] = array("like", "%".I("request.value")."%");
            }
        }
        return $where;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("quit")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("quit")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("quit")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("quit")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}